package top.huhuiyu.springboot3.p2301.service.impl;

import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import top.huhuiyu.springboot3.p2301.base.R;
import top.huhuiyu.springboot3.p2301.service.MailService;
import top.huhuiyu.springboot3.p2301.service.RedisService;
import top.huhuiyu.springboot3.p2301.util.DateUtils;
import top.huhuiyu.springboot3.p2301.util.EncryptorUtils;

import java.util.Calendar;

@Service
@RequiredArgsConstructor
@Slf4j
public class MailServiceImpl implements MailService {
    private final JavaMailSender mailSender;
    private final RedisService redisService;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    @Override
    public R<String> sendMailCode(String email) throws Exception {
        // 验证邮箱是否存在校验码
        String key = String.format(EMAIL_KEY, email);
        if (redisService.has(key)) {
            return R.fail("请勿重复发送验证码", null);
        }
        // 生成验证码
        String code = EncryptorUtils.makeRandNumber(6);
        // 发送邮件
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(email);
        helper.setSubject("邮箱验证码");
        // 处理过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, EMAIL_CODE_EXPIRE);
        helper.setText(String.format(EMAIL_TEMPLATE, code, DateUtils.format(calendar.getTime())), true);
        mailSender.send(message);
        // 保存到redis
        redisService.save(key, code, EMAIL_CODE_EXPIRE);
        return R.ok("验证码已发送", "");
    }

    @Override
    public R<String> validateMailCode(String email, String code) {
        String key = String.format(EMAIL_KEY, email);
        String codeInRedis = redisService.load(key, String.class);
        if (codeInRedis == null) {
            return R.fail("验证码不存在或者已经过期", null);
        }
        if (!codeInRedis.equals(code)) {
            return R.fail("验证码错误", null);
        }
        redisService.delete(key);
        return R.ok("验证成功", null);
    }
}
